<!--
 * @Description: 
 * @Version: @1.0.0
 * @Autor: LuLu
 * @Date: 2023-06-30 18:16:01
 * @LastEditors: LuLu
 * @LastEditTime: 2025-03-13 17:12:49
-->
<!-- 模板 -->
<template>
  <div class="cooperationScale">
    <div class="box">
      <div class="btn">
        <!-- <el-button type="primary" icon="el-icon-plus" size="small" @click="add">添加</el-button> -->
        <div>
          <el-form
            :inline="true"
            :model="params"
            size="small"
            label-width="100px"
          >
            <el-form-item label="测量表名称:">
              <el-input
                v-model="params.tableName"
                placeholder="输入测量表名称"
                clearable
                @clear="search"
              />
            </el-form-item>
            <el-form-item label="合作商:">
              <el-input
                v-model="params.name"
                placeholder="输入合作商"
                clearable
                @clear="search"
              />
              <!-- <el-select v-model="params.measureId"  placeholder="请选择" clearable filterable @change="search" >
                            <el-option
                            v-for="item in options1"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                            >
                            </el-option>
                        </el-select> -->
            </el-form-item>
            <span style="margin-left: 10px">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="search"
                >搜索</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="small"
                @click="add"
                >添加</el-button
              >
              <!-- <el-button type="primary" icon="el-icon-plus" size="small" @click="add" >导出</el-button> -->
            </span>
          </el-form>
        </div>
      </div>
      <el-card>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column
            prop="name"
            label="合伙人"
            align="center"
            width="220"
          >
          </el-table-column>
          <el-table-column
            prop="tableName"
            label="量表名字"
            align="center"
            width="280"
          >
          </el-table-column>
          <el-table-column
            prop="allCount"
            label="测试码数量"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="useCount"
            label="已测试数量"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="开通时间"
            align="center"
            width="180"
          >
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" width="80">
            <template slot-scope="scope">
              <!-- {{scope.row.status == 0?'禁用':scope.row.status == 1?'正常':''}} -->
              <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
              <el-tag type="danger" v-if="scope.row.status == 0">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="content"
            label="测评单位名称"
            align="center"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column label="操作" align="center" width="375">
            <template slot-scope="scope">
              <el-button
                @click="handleUpdateClick(scope.row)"
                type="primary"
                icon="el-icon-edit"
                size="small"
                plain
                >修 改</el-button
              >
              <el-button
                v-show="scope.row.status == 1"
                @click="handleCooperationClick(scope.row)"
                type="danger"
                size="small"
                icon="el-icon-warning-outline"
                plain
              >
                暂停合作</el-button
              >
              <el-button
                v-show="scope.row.status == 0"
                @click="handleAddClick(scope.row)"
                type="primary"
                size="small"
                icon="el-icon-warning-outline"
                plain
              >
                重启合作</el-button
              >
              <el-button
                @click="daochu(scope.row)"
                type="success"
                icon="el-icon-download"
                class="handle-del mr10"
                size="small"
                plain
                >导 出</el-button
              >
              <el-button @click="handleDeleteClick(scope.row)" type="danger" size="small" icon="el-icon-delete" plain>删除</el-button>
              <!-- <el-button @click="handleLookClick(scope.row)" type="primary" size="small" icon="el-icon-view" plain>查看报表</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="params.pageNum"
        :limit.sync="params.pageSize"
        @pagination="getGroupList"
      />
    </div>
    <!-- 添加弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="35%"
      :before-close="handleClose"
    >
      <el-form label-width="110px" :model="form" :rules="rules" ref="form">
        <el-form-item label="用户" prop="name" v-if="showBtn">
          <el-input
            v-model="form.name"
            disabled
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择用户" prop="name" v-else>
          <el-select
            v-model="form.name"
            placeholder="请选择"
            @change="changeValue"
            style="width: 300px"
          >
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择量表" prop="tableId">
          <el-select
            v-model="form.tableId"
            placeholder="请选择"
            @change="changeValue1"
            style="width: 300px"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测试码人数" prop="allCount">
          <el-input
            v-model.number="form.allCount"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="测评单位名称" prop="allCount">
          <el-input v-model="form.content" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="groupPhone">
          <el-input
            v-model.number="form.groupPhone"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="单位地址" prop="groupUnit">
          <el-input
            v-model.number="form.groupUnit"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系二维码" prop="groupQrCode">
          <el-upload
            :headers="headers"
            class="avatar-uploader"
            :action="upImage + '/table/upload'"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
          >
            <img
              v-if="form.groupQrCode"
              :src="form.groupQrCode"
              class="avatar"
            />

            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { blobValidate } from "@/utils/ruoyi";
import { getToken } from "@/utils/auth";

import {
  getList,
  getAdd,
  getDsc,
  getUpdate,
  getWxList,
  getWxDsc,
  getStopDsc,
  getExport,
  getStartDsc,
  delGroup
} from "@/api/partner/index";
// import {getWxList,getWxUpdate,getWxDsc} from '@/api/partner/index'
import { getList1, getDetails1 } from "@/api/table/table";

export default {
  name: "",
  data() {
    return {
      tableData: [],
      ceshidata: "222222",
      dialogVisible: false,
      form: {
        openid: undefined,
        name: "",
        tableName: "",
        groupQrCode: "",
        groupPhone: "",
        groupUnit: "",
      },
      upImage: process.env.VUE_APP_BASE_API,

      headers: { Authorization: "Bearer " + getToken() },
      baseURL: process.env.VUE_APP_BASE_API,

      rules: {
        name: [{ required: true, message: "请选择用户", trigger: "change" }],
        tableId: [
          { required: true, message: "请选择测量表", trigger: "change" },
        ],
        allCount: [
          {
            type: "number",
            required: true,
            message: "请输入测试码人数",
            trigger: "blur",
          },
        ],
        content: [
          {required: true, message: '请输入测评单位名称', trigger: 'blur' }
        ],
      },
      params: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      paramsFlag: 0,
      showBtn: true,
      options: [],
      options1: [],
      title: "",
    };
  },
  props: [],
  components: {},
  computed: {},
  filters: {},
  methods: {
    // 导出
    daochu(row) {
      // console.log(row);
      // return
      if (row.useCount <= 0) {
        this.$message.warning("暂无测试数据");
      } else {
        getExport(row.identification).then((res) => {
          if (res.code == 200) {
            this.downloadFile(res.msg,row);
          }
        });
      }
    },
    // downloadFile 方法，用来下载文件
    downloadFile(fileName,row) {
      const url =
        this.baseURL +
        `/common/download?fileName=${encodeURIComponent(fileName)}&delete=true`;
      axios({
        method: "get",
        url: url,
        responseType: "blob", // 确保响应类型是 Blob（二进制数据）
        headers: this.headers, // 如果需要认证的话
      })
        .then(async (res) => {
          const isLogin = await blobValidate(res.data);
          if (isLogin) {
            // console.log(res);
            const blob = new Blob([res.data]); // 将响应数据转换为 Blob 对象
            const fileName = decodeURI(res.headers["content-disposition"]); // 从响应头获取文件名
            this.saveAs(blob, `${row.content}_合作量表.xlsx`); // 使用 file-saver 下载文件
          } else {
            this.printErrMsg(res.data); // 如果不是有效的文件，打印错误信息
          }
        })
        .catch((error) => {
          console.error("下载文件失败：", error);
        });
    },
    // 下载文件的辅助函数
    saveAs(blob, fileName) {
      saveAs(blob, fileName); // 使用 file-saver 库保存文件
    },
    // 错误消息处理
    async printErrMsg(data) {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = rspObj.msg || "下载失败"; // 错误信息
      Message.error(errMsg); // 显示错误信息
    },
    //上传图片
    handleAvatarSuccess(res, file) {
      this.form.groupQrCode =
        "https://9001rzsxy.oss-cn-beijing.aliyuncs.com" + res.data;
      if (res.code == 200) {
        this.$message.success("上传成功");
      }
      this.$forceUpdate(); //手动更新data
    },
    // 搜索
    search() {
      this.$set(this.params, "pageNum", 1);
      this.paramsFlag = 0;
      this.getGroupList();
    },
    // 查看
    handleLookClick(row) {
      console.log(row);
    },
    // 停止合作
    handleCooperationClick(row) {
      const id = row.id;
      // console.log(id)
      this.$confirm("是否确认停止合作?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return getStopDsc(id);
        })
        .then(() => {
          this.getGroupList();
          this.$message.success("操作成功");
        })
        .catch(function () {});
    },
     handleDeleteClick(row){
        this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delGroup(row.id).then(res => {
          if (res.code == 200) {
            this.getGroupList()
          }
        });
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // （启用）
    handleAddClick(row) {
      const id = row.id;
      // console.log(id)
      this.$confirm("是否确认启用合作?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return getStartDsc(id);
        })
        .then(() => {
          this.getGroupList();
          this.$message.success("操作成功");
        })
        .catch(function () {});
    },
    // 修改
    handleUpdateClick(row) {
      this.title = "修改";
      this.dialogVisible = true;
      this.form = row;
      this.showBtn = true;
    },
    onSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            getUpdate(this.form).then((res) => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.dialogVisible = false;
                this.getGroupList();
              }
            });
          } else {
            getAdd(this.form).then((res) => {
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.dialogVisible = false;
                this.getGroupList();
              }
            });
          }
        }
      });
    },
    // 用户列表
    getList() {
      getWxList().then((res) => {
        let a = res.rows;
        for (let i = 0; i < a.length; i++) {
          if (a[i].agentType == 3) {
            this.options1.push(a[i]);
          }
        }
        // console.log(this.options1);
      });
    },
    // 获取列表
    getGroupList() {
      getList(this.params).then((res) => {
        if (res.code == 200) {
          // console.log(res);
          this.tableData = res.rows;
          this.total = res.total;
        }
      });
    },
    add() {
      this.title = "添加";
      this.dialogVisible = true;
      this.showBtn = false;
      this.form = {};
    },
    // 测量表详情
    changeValue1(val) {
      getDetails1(val).then((res) => {
        if (res.code == 200) {
          // console.log(res);
          this.form.tableName = res.data.name;
        }
      });
    },
    // 用户详情
    changeValue(val) {
      // console.log(val);
      getWxDsc(val).then((res) => {
        if (res.code == 200) {
          // console.log(res);
          this.form.name = res.data.name;
          this.form.openid = res.data.openid;
          // console.log(this.form.name);
        }
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.getGroupList();
    },
    // 获取所有测量表
    getTableList() {
      getList1().then((res) => {
        if (res.code == 200) {
          // console.log(res);
          this.options = res.rows;
        }
      });
    },
  },
  created() {
    this.params.name = this.$route.query.name;
    this.getList();
    this.getGroupList();
    this.getTableList();
  },
  mounted() {},
};
</script>

<style rel="stylesheet/scss" lang="scss">
.box {
  margin: 10px;
  .btn {
    margin-top: 20px;
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.table {
  padding-bottom: 20px;
}
.box {
  margin: 10px;
  .btn {
    display: flex;
    // align-content: center;
    margin-top: 20px;
  }
}
.el-tooltip__popper {
  max-width: 60% !important;
}
.el-tooltip__popper,
.el-tooltip__popper.is-dark {
  max-width: 50% !important;
  line-height: 24px;
  color: #fff !important;
  background-color: rgb(48, 65, 86) !important;
}
.avatar-uploader .el-upload {
  width: 148px;
  height: 148px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border: 1px dashed #ccc;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.el-textarea__inner {
  height: 80px !important;
}
.select {
  // display: block;
  margin-bottom: 10px;
  // vertical-align: middle;
}
.el-row {
  margin-bottom: 20px !important;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
